export const Location = {
	callback: null,
	isLocationTool: false,
	isFirst: false,
	isInit: false,
	loopValidateGps(callBack) {
		const _this = this
		let lastTool = true
		setInterval(()=> {
			_this.handleValidateGps((tool)=> {
				console.log("权限=======>>>>", tool);
				if(lastTool === tool) return
				lastTool = tool
				callBack(tool)
			})
		}, 5000)
	},
	handleValidateGps(callBack) {
		const _this = this
		_this.validateGps().then((tool) => {
			if (tool) {
				callBack(true)
			} else {
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						callBack(true)
					},
					fail(error) {
						callBack(false)
					}
				});
			}
		})
	},
	validateGps() {
		const _this = this
		return new Promise((resolve) => {
			let sysAuthorize = _this.sysLocationAuthorize()
			let appAuthorize = _this.appLocationAuthorize()
			if (!sysAuthorize || !appAuthorize) {
				resolve(false)
			}
			resolve(true)
		})
	},
	verifyLocationAuthorize(type) {
		// #ifdef H5
		return true
		// #endif
		const _this = this
		if (type !== "init" && _this.isFirst) return
		let sysAuthorize = _this.sysLocationAuthorize()
		let appAuthorize = _this.appLocationAuthorize()
		if (!sysAuthorize || !appAuthorize) {
			// uni.showModal({
			//   title: '温馨提示',
			//   content: '获取权限失败，需要获取您的地理位置才能为您提供更好的服务！',
			//   showCancel: false,
			//   confirmText: '前往设置',
			//   success: res => {
			//     if (res.confirm) {
			//       _this.openSetting()
			//     }
			//   }
			// });
		} else {
			// uni.showToast({
			//   title: '已获得定位权限',
			//   icon: 'none'
			// })
			_this.isFirst = false
			_this.startLocation()
		}

	},
	sysLocationAuthorize() {
		// #ifdef H5
		return false
		// #endif

		let system = uni.getSystemInfoSync(); // 获取系统信息
		if (system.platform === 'android') { // 判断平台
			let context = plus.android.importClass("android.content.Context");
			let locationManager = plus.android.importClass("android.location.LocationManager");
			let main = plus.android.runtimeMainActivity();
			let mainSvr = main.getSystemService(context.LOCATION_SERVICE);
			let syslocation = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)
			return syslocation
		} else if (system.platform === 'ios') {
			let cllocationManger = plus.ios.import("CLLocationManager");
			let enable = cllocationManger.locationServicesEnabled();
			let status = cllocationManger.authorizationStatus();
			plus.ios.deleteObject(cllocationManger);

			if (enable && status != 2) {
				return true
			}
			return false
		}
	},
	appLocationAuthorize() {
		const appAuthorizeSetting = uni.getAppAuthorizeSetting()
		console.log(appAuthorizeSetting)
		if (appAuthorizeSetting.locationAccuracy === "unsupported" || appAuthorizeSetting.locationAuthorized ===
			"denied") {
			console.log("定位权限没开")
			return false
		} else {
			return true
		}
	},
	openSetting() {
		const _this = this
		let system = uni.getSystemInfoSync(); // 获取系统信息
		if (system.platform === 'android') { // 判断平台
			let main = plus.android.runtimeMainActivity();
			let Intent = plus.android.importClass("android.content.Intent");
			let mIntent = new Intent("android.settings.LOCATION_SOURCE_SETTINGS");
			main.startActivity(mIntent);
		} else if (system.platform === 'ios') {
			let UIApplication = plus.ios.import("UIApplication");
			let application2 = UIApplication.sharedApplication();
			let NSURL2 = plus.ios.import("NSURL");
			let setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
			application2.openURL(setting2);
			plus.ios.deleteObject(setting2);
			plus.ios.deleteObject(NSURL2);
			plus.ios.deleteObject(application2);
		}
		_this.isLocationTool = false
		_this.isFirst = false
	},
	initLocation(callback) {
		// #ifdef H5
		return true
		// #endif
		const _this = this
		if (_this.isInit) return
		_this.isInit = true
		_this.callback = callback
		_this.isFirst = true
		uni.onLocationChange(function(res) {
			_this.resLocation(res)
		});
		uni.onLocationChangeError((errRes) => {
			console.log("定位出错了", errRes)
		})
		this.getLocation()
	},
	getLocation() {
		const _this = this
		uni.getLocation({
			type: 'gcj02',
			// isHighAccuracy: true,
			// geocode: true,
			success: function(res) {
				_this.startLocation()
			},
			fail(error) {
				console.log(error.errMsg)
				_this.verifyLocationAuthorize("init")
			}
		});
	},
	loopGetLocation(callback) {
		const _this = this
		uni.getLocation({
			type: 'gcj02',
			// isHighAccuracy: true, // 开启高精度定位
			// altitude: true, // 返回高度信息
			// geocode: true, // 是否解析地址信息
			success: function(res) {
				callback(res)
			},
			fail(error) {
				_this.verifyLocationAuthorize("init")
			}
		});
	},
	resLocation(res) {
		if (this.callback) this.callback(res)
	},
	startLocation() {
		const _this = this
		if (this.isLocationTool) return
		this.isLocationTool = true

		uni.startLocationUpdate({
			needFullAccuracy: true,
			success: res => console.log('开启接收位置消息成功'),
			fail: err => console.error('开启接收位置消息失败：', err),
			complete: msg => console.log('调用开启接收位置消息 API 完成')
		});
	},
	stopLocation() {
		this.isLocationTool = false

		uni.stopLocationUpdate({
			success: res => console.log('关闭小程序接收位置消息成功'),
			fail: err => console.error('关闭小程序接收位置消息失败：', err),
			complete: msg => console.log('调用关闭小程序接收位置消息 API 完成')
		});

		uni.offLocationChangeError((errRes) => {
			console.log("定位出错了监听关闭", errRes)
		})

		uni.offLocationChange(function(res) {
			console.log('+++++offLocationChange：' + res);
		});

	},
}